package com.live.shop.scene.ws;

import android.content.Context;
import android.util.Log;

import com.live.shop.tool.GetUtil;
import com.live.shop.tool.MD5Util;

import org.greenrobot.eventbus.EventBus;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class WsServer extends WebSocketServer {

    public static Collection<WebSocket> collections;
    static Context mContect;
    static WsServer ws;

    public WsServer(InetSocketAddress host){
        super(host);
    }

    public static void ready(Context context,String url, int port){
        collections = new ArrayList<>();
        mContect = context;
        InetSocketAddress myHost = new InetSocketAddress(url, port);
        WsServer newWs = new WsServer(myHost);
        try {
            newWs.setReuseAddr(true);
            newWs.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
        WsServer.ws = newWs;
    }
    public static void Stop() {
        try {
            if(ws != null){
                ws.stop();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void sendFile(String filePath) {
        try {
            File file = new File(filePath);
            if(!file.exists()){
                Log.d(GetUtil.TAG,"[文件本地不存在]"+filePath);
                EventBus.getDefault().post(new WsMessageEvent(WsStatus.onError,"【文件本地不存在】"+filePath));
                return;
            }
            long fileSize = file.length();
            FileInputStream fis = new FileInputStream(file);
            byte[] bt = new byte[1024];
            long totalLength = 0;
            int length;
            while ((length = fis.read(bt)) != -1) {
                totalLength += length;
                int progress = (int)(totalLength/(double)fileSize*100);
                if(progress%10 == 0) EventBus.getDefault().post(new WsMessageEvent(WsStatus.onMessageProgress,progress));
                ws.broadcast(bt,collections);
            }
            fis.close();

            //传输完毕 发送关闭流
            try {
                JSONObject json = new JSONObject();
                json.put("command",WsStatus.transFileOver);
                json.put("param",filePath);
                SendMsg(json.toString());
            }catch (Exception e){
                e.printStackTrace();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    //发送消息
    public static void SendMsg(String string) {
        try {
            //Collection<WebSocket> clients,指定发送到哪个客户端
            ws.broadcast(string,collections);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    public void onStart() {
        EventBus.getDefault().post(new WsMessageEvent(WsStatus.onStart,"[服务端]服务器已就绪"));
    }

    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        //校验握手信息 handshake.getResourceDescriptor()  =>  /getConnect?timestamp="+timestamp+"&sign="+sign
        String header = handshake.getResourceDescriptor();
        String timePattern = "timestamp=([^&]*)";
        String signPattern = "sign=([^&]*)";
        Pattern tPattern = Pattern.compile(timePattern);
        Pattern sPattern = Pattern.compile(signPattern);
        Matcher timeMa = tPattern.matcher(header);
        Matcher signMa = sPattern.matcher(header);
        if(timeMa.find()) {
            String timestamp = timeMa.group(1);
            if(signMa.find()) {
                String submitSign = signMa.group(1);
                String signCheck = MD5Util.encrypt(mContect.getPackageName()+"junge"+timestamp);
                if(submitSign.equals(signCheck)){
                    if(collections.size() >= 1){
                        conn.close(1000,"已达最大连接数");
                    }else{
                        collections.add(conn);
                        EventBus.getDefault().post(new WsMessageEvent(WsStatus.onOpen,"[服务端]onOpen："+getRemoteSocketAddress(conn)));
                    }
                }else{
                    conn.close(1000,"Inconsistent signature");
                }
            }else{
                conn.close(1000,"Missing sign parameter");
            }
        }else{
            conn.close(1000,"Missing timestamp parameter");
        }
    }

    @Override
    public void onMessage(WebSocket conn, String message) {
        EventBus.getDefault().post(new WsMessageEvent(WsStatus.onMessageString,message));
    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        for (WebSocket w:collections) {
            if(w.getRemoteSocketAddress().equals(conn.getRemoteSocketAddress())){
                collections.remove(w);
                EventBus.getDefault().post(new WsMessageEvent(WsStatus.onClose,"[服务端]onClose：code["+code+"],reason["+reason+"]"));
            }
        }
    }
    @Override
    public void onError(WebSocket conn, Exception ex) {
        EventBus.getDefault().post(new WsMessageEvent(WsStatus.onError,"[服务端]onError："+ex.toString()));
    }
}

